import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;

import javax.mail.internet.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import java.sql.*;

import java.util.Properties;

public class Email {
    public static void sendMail (String target_address,String host,String home_address,String password)throws MessagingException{
        Properties props = System.getProperties();
        props.put("mail.smtp.host",host);
        props.put("mail.smtp.auth","true");
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(home_address,password);
            }
        });

        //向目标邮箱发送的具体信息
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(home_address));
        message.addRecipient(Message.RecipientType.TO,new InternetAddress(target_address));
        message.setSubject("JAVA");
        message.setText("Do you like me?");
        Transport.send(message);
    }

    //创建附件
    public static MimeBodyPart createAttachment(String filename)throws MessagingException {
        MimeBodyPart attachmentPart = new MimeBodyPart();
        FileDataSource fileDataSource = new FileDataSource(filename);
        attachmentPart.setDataHandler(new DataHandler(fileDataSource));
        attachmentPart.setFileName(fileDataSource.getName());
        return attachmentPart;
    }

    //创建含有图片的正文部分
    public static MimeBodyPart createContent(String body,String filename) throws MessagingException {
        MimeBodyPart contentPart = new MimeBodyPart();
        MimeMultipart contentMulti = new MimeMultipart("related");

        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent(body,"text/html;charset=utf8");
        contentMulti.addBodyPart(textPart);

        MimeBodyPart imagePart = new MimeBodyPart();
        FileDataSource fileDataSource = new FileDataSource(filename);
        imagePart.setDataHandler(new DataHandler(fileDataSource));
        imagePart.setContentID("imagetest");
        contentMulti.addBodyPart(imagePart);

        contentPart.setContent(contentMulti);
        return contentPart;
    }

    public static void sendExtraMail(String target_address,String host,String home_address,String password) throws MessagingException{
        Properties props = System.getProperties();
        props.put("mail.smtp.host",host);
        props.put("mail.smtp.auth","true");
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(home_address,password);
            }
        });

        String body = "<h4>附件与图片发送测试</h4> </br>"
                + "<img src = \"cid:imagetest\"></a>";

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(home_address));
        message.addRecipient(Message.RecipientType.TO,new InternetAddress(target_address));
        message.setSubject("Image and Attachment test");

        MimeBodyPart attachment = createAttachment("data/filetest.txt");
        MimeBodyPart content = createContent(body,"data/imagetest.jpg");

        MimeMultipart allPart = new MimeMultipart("mixed");
        allPart.addBodyPart(attachment);
        allPart.addBodyPart(content);

        message.setContent(allPart);
        Transport.send(message);
    }

    public static void receiveMail(String pop3,String protocol,String home_address,String password,int port) throws MessagingException,IOException{
        Properties props = System.getProperties();
        props.put("mail.smtp.host",pop3);
        props.put("mail.smtp.auth","true");
        Session session = Session.getDefaultInstance(props,null);
        Store store = null;
        Folder folder = null;

        URLName url = new URLName(protocol,pop3,port,null,home_address,password);
        store = session.getStore(url);
        store.connect();
        folder = store.getFolder("inbox");
        folder.open(Folder.READ_ONLY);
        Message[] messages = folder.getMessages();
        int Messagecount = messages.length;

        //获取的邮件内容展示，包括简单的语义判断
        for(int i=0;i<Messagecount;i++){
            StringBuffer content = new StringBuffer(30);
            MimeMessage msg = (MimeMessage) messages[i];
            getMailTextContent(msg,content);
            System.out.println("----第"+msg.getMessageNumber()+"封邮件----");
            System.out.println("主题:"+msg.getSubject());
            System.out.println("发件人:"+getFrom(msg));
            System.out.println("邮件正文：" + (content.length() > 16 ? content.substring(0,16): content));
            if(content.indexOf("Yes")!=-1||content.indexOf("yes")!=-1){
                System.out.println("The reply is 'Yes'!");
            }
            else if(content.indexOf("No")!=-1||content.indexOf("no")!=-1){
                System.out.println("The reply is 'No'!");
            }
            else{
                System.out.println("Don't understand the meaning now!");
            }
        }

        folder.close(false);
        store.close();
    }

    //获取发件人信息
    public static String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException {
        String from = "";
        Address[] froms = msg.getFrom();
        if (froms.length < 1)
            throw new MessagingException("没有发件人!");

        InternetAddress address = (InternetAddress) froms[0];
        String person = address.getPersonal();
        if (person != null) {
            person = MimeUtility.decodeText(person) + " ";
        } else {
            person = "";
        }
        from = person + "<" + address.getAddress() + ">";

        return from;
    }

    //获取邮件的正文内容
    public static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {
        boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;
        if (part.isMimeType("text/*") && !isContainTextAttach) {
            content.append(part.getContent().toString());
        } else if (part.isMimeType("message/rfc822")) {
            getMailTextContent((Part)part.getContent(),content);
        } else if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                getMailTextContent(bodyPart,content);
            }
        }
    }

    public static void main(String[] args) throws Exception{
        Connection conn = null;
        String driver = "com.mysql.jdbc.Driver";
        String URL = "jdbc:mysql://localhost:3306/homework_4";
        String USER = "root";
        String PASSWORD = "";
        Class.forName(driver);
        conn = DriverManager.getConnection(URL,USER,PASSWORD);             //连接数据库

        String sql = "select * from address where id=?";
        PreparedStatement psmt = conn.prepareStatement(sql);
        psmt.setInt(1,1);
        ResultSet resultSet = psmt.executeQuery();     //选择数据库中的第一个邮箱信息

        String host = null;
        String pop3 = null;
        String protocol = null;
        String home_address = null;
        String password = null;
        int port = 0;

        while (resultSet.next()){
            host = resultSet.getString("host");
            pop3 = resultSet.getString("pop3");
            protocol = resultSet.getString("protocol");
            home_address = resultSet.getString("home_address");
            password = resultSet.getString("password");
            port = resultSet.getInt("port");
        }                                            //获取邮件信息

        //Email.sendMail("441496348@qq.com",host,home_address,password);        //发送邮件
        //Email.sendExtraMail("441496348@qq.com",host,home_address,password);   //发送含有附件与图片的邮件
        Email.receiveMail(pop3,protocol,home_address,password,port);          //接收邮件

        conn.close();             //释放数据库连接
    }
}
